package com.atguigu.Sink;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.been.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;

/**
 * @author wky
 * @create 2021-07-14-18:27
 */
public class Sink_Redis {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment senv = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> source = senv.socketTextStream("hadoop102", 9998);
        SingleOutputStreamOperator<WaterSensor> map = source.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String s) throws Exception {
                String[] split = s.split(",");
                WaterSensor waterSensor = new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));

                return waterSensor;
            }
        });
        FlinkJedisPoolConfig.Builder builder = new FlinkJedisPoolConfig.Builder();
        FlinkJedisPoolConfig jedisPoolConfig = builder.setHost("hadoop102")
                .setPort(6379)
                .setMaxTotal(100)
                .setTimeout(10000).build();
        map.addSink(new RedisSink<>(jedisPoolConfig,new MyRedisMap()));
        senv.execute();
    }
    public static class MyRedisMap implements RedisMapper<WaterSensor>{

        // 返回存在Redis中的数据类型  存储的是Hash, 第二个参数是外面的key
        @Override
        public RedisCommandDescription getCommandDescription() {
            return new RedisCommandDescription(RedisCommand.HSET,"sensor");
        }
        // 从数据中获取Key: Hash的Key
        @Override
        public String getKeyFromData(WaterSensor data) {
            return data.getId();
        }
        // 从数据中获取Value: Hash的value
        @Override
        public String getValueFromData(WaterSensor data) {
            return JSON.toJSONString(data);
        }
    }
}
